<?php
class Tourismgoodsbargaining extends CS_Controller
{
    private $uidArray = array();
    private $priceProfit = array();
    
    public function _init(){
        $this->load->helper('profit');
        $this->load->library('pagination');
        $this->load->model('tourism_goods_bargaining_model', 'tourism_goods_bargaining');
        $this->load->model('tourism_goods_profit_model', 'tourism_goods_profit');
        $this->load->model('tourism_goods_base_model', 'tourism_goods_base');
        $this->load->model('user_model', 'user');
        $this->load->model('user_type_model', 'user_type');
    }
    
    public function grid($pg = 1){
        $num = ($pg-1)*20;
        $goodsAttrId = $this->input->get('goods_attr_id');
        
        $config['base_url']    = base_url('tourismgoodsbargaining/grid');
        $config['total_rows']  = $this->tourism_goods_bargaining->total($goodsAttrId);
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_list']   = $this->pagination->create_links();
        $data['page_list'] = $this->tourism_goods_bargaining->page_list($num, $goodsAttrId);
        $data['all_rows']  = $config['total_rows'];
        $data['pg_now']    = $pg;
        $this->load->view('tourismgoodsbargaining/grid', $data);
    }
    
    public function add(){
        $goods_attr_id = $this->input->get('goods_attr_id');
        $result = $this->tourism_goods_base->findByAttrId($goods_attr_id);
        if($result->num_rows() <= 0){
            $this->redirect('tourismgoodsbargaining/grid');
        }
        $data['info'] = $result->row();
        $this->load->view('tourismgoodsbargaining/add', $data);
    }
    
    public function addPost(){
        $this->db->trans_start();
        foreach ($this->uidArray as $value) {
            $barganiningId = $this->tourism_goods_bargaining->add( $this->input->post() ,$value);
            $resultId = $this->tourism_goods_profit->add($barganiningId, $this->input->post());
        }
        $this->db->trans_complete();
        
        if ($this->db->trans_status() === FALSE) {
            $this->session->set_flashdata('error', '保存失败！');
            $this->jsen('tourismgoodsbargaining/grid?goods_attr_id='.$this->input->post('goods_attr_id'), true);
        } else {
            $this->session->set_flashdata('success', '保存成功！');
            $this->jsen('tourismgoodsbargaining/grid?goods_attr_id='.$this->input->post('goods_attr_id'), true);
        }
    }
    
    public function edit($id){
        $data['userType'] = $this->user_type->get_list('Y', array('8192', '134217728'));
        $data['bargaining'] = $this->tourism_goods_bargaining->findById($id)->row();
        $data['profit'] = $this->tourism_goods_profit->findByArray(array('goods_attr_id'=>$id,'status'=>2));
        $this->load->view('tourismgoodsbargaining/edit', $data);
    }
    
    public function editPost(){
        $this->db->trans_start();
        $this->tourism_goods_bargaining->edit($this->input->post());
        $this->tourism_goods_profit->delete(array('goods_attr_id'=>$this->input->post('bargaining_id'), 'status'=>2));
        $this->tourism_goods_profit->add($this->input->post('bargaining_id'), $this->input->post());
        $this->db->trans_complete();
        
        if ($this->db->trans_status() === FALSE) {
            $this->session->set_flashdata('error', '保存失败！');
            $this->jsen('tourismgoodsbargaining/grid?goods_attr_id='.$this->input->post('goods_attr_id'), true);
        } else {
            $this->session->set_flashdata('success', '保存成功！');
            $this->jsen('tourismgoodsbargaining/grid?goods_attr_id='.$this->input->post('goods_attr_id'), true);
        }
    }
    
    public function delete($id){
        $this->db->trans_start();
        $is_delete = $this->tourism_goods_bargaining->delete($id);
        $resultId  = $this->tourism_goods_profit->delete(array('goods_attr_id'=>$id, 'status'=>2));
        $this->db->trans_complete();
        if ($is_delete && $resultId)
        {
            $this->success('tourismgoodsbargaining/grid', array('goods_attr_id'=>$this->input->get('goods_attr_id')), '删除成功！');
        } else {
            $this->error('tourismgoodsbargaining/grid', array('goods_attr_id'=>$this->input->get('goods_attr_id')), '删除失败！');
        }
    }
    
    public function ajaxValidate()
    {
        if (!$this->input->post('bargaining_id')) {
            //是否存在这些用户
            $error = $this->validateUserName();
            if (!empty($error)) {
                $this->jsen($error);
            }
    
            //验证这些用户是否议过价
            $error = $this->validateSeller();
            if (!empty($error)) { //如果不为空，则此用户议过价
                $this->jsen($error);
            }
    
            $error = $this->validateProviderUid();
            if (!empty($error)) { //验证供应商uid
                $this->jsen($error);
            }
        }
        //验证数据的正确性
        $error = $this->validataPostInfo();
        if (!empty($error)) {
            $this->jsen($error);
        }
    
        //验证手续费分钱对不对
        $error = $this->validateProfit();
        if (!empty($error)) {
            $this->jsen($error);
        }
        //存在议价ID  表示是编辑   不存在是添加议价
        if ($this->input->post('bargaining_id')) {    //议价ID
            $this->editPost();
        } else {
            $this->addPost();
        }
    }
    
    private function jsen($error, $flag=false)
    {
        if (is_array($error)) {
            $erro = '';
            foreach ($error as $er) {
                $erro .= '<p>'. $er . '</p>';
            }
            $error = $erro;
        }
        echo json_encode(array(
                'status'=> $flag,
                'msg'   => $error
        ));exit;
    }
    
    public function validateUserName()
    {
        $error = array();
        $seller_name = trim(strtr($this->input->post('user_name'), array('，'=>',')), ',');
        if (strpos($seller_name, ',') === false) {
            $sellerArray = $seller_name;
        } else {
            $sellerArray = explode(',', $seller_name);
        }
        if (empty($sellerArray)) {
            return $error[] = '分销商不可为空！';
        }
        if (!is_array($sellerArray)) {
            $sellerArray = array($sellerArray);
        }
        $resultUtitSeller = $this->user->findByIds(array('user_name'=>$sellerArray, 'user_type'=>UTID_SELLER)); //用户类型为分销商
        if (!$resultUtitSeller) {
            return $error[] = implode($sellerArray, ',').'分销商用户不存在！';
        }
        $sellerQuery = $this->getUserNameUid($resultUtitSeller);
        $diffArray = array_diff($sellerArray, $sellerQuery);
        if (!empty($diffArray)) {
            return $error[] = '分销商为 "'.implode($diffArray, ',').'" 的用户不存在';
        }
    
        $this->uidArray = array_flip($sellerQuery);  //key和值交换
        return $error;
    }
    
    private function getUserNameUid($result)
    {
        $sellerQuery = array();
        foreach ($result->result() as $item) {
            $sellerQuery[$item->uid] = $item->user_name;
        }
        return $sellerQuery;
    }
    
    public function validateSeller()
    {
        $error = array();
        $goodsAttrId = $this->input->post('goods_attr_id');
        if (!$goodsAttrId) {
            return $error[] = '产品编号丢失，请重新操作。';
        }
        $result = $this->tourism_goods_bargaining->findByArray(array('goods_attr_id'=>$goodsAttrId, 'seller_uid'=>$this->uidArray));

        $userName = array();
        if ($result) {
            foreach ($result->result() as $value) {
                $userName[] = array_search($value->seller_uid, $this->uidArray);
            }
        }
        if (!empty($userName)) {
            return $error[] = '用户 "'.implode(',', $userName).'" 已经议过价了.';
        }
        return $error;
    }
    
    public  function  validateProviderUid(){
        $error = array();
        $goodsAttrId = $this->input->post('goods_attr_id');
        if (!is_numeric($this->input->post('provider_uid'))) {
            $error[] = '供应商uid不可为空，只能为数字。';
        } else {
            $result = $this->user->findByIds(array('uid'=>$this->input->post('provider_uid'), 'user_type'=>UTID_PROVIDER));
            if (!$result) {
                $error[] = '供应商用户('.$this->input->post('provider_uid').')不存在或者该用户不是供应商！';
            }
            $goodAttr = $this->tourism_goods_base->findByAttrId($goodsAttrId);
            $uid = $goodAttr->row()->uid;
            if ($uid != $this->input->post('provider_uid')){
                $error[] = '供应商UID('.$this->input->post('provider_uid').')填写的与商品供应商'.$uid.'不符';
            }
        }
        return $error;
    }
    
    public function validataPostInfo()
    {
        $error = array();
        if (!is_numeric($this->input->post('shop_price'))) {
            $error[] = '销售价不可为空，只能为数字。';
        }
        if (!is_numeric($this->input->post('supply_price'))) {
            $error[] = '结算价不可为空，只能为数字。';
        }
        if (!is_numeric($this->input->post('poundage'))) {
            $error[] = '总手续费不可为空，只能为数字。';
        }
        $provide_total = $this->input->post('supply_price')+$this->input->post('poundage')+$this->input->post('prosecond_profit');//结算价+手续费+二级供应价
        if (bccomp($this->input->post('shop_price'), $provide_total,3) == -1) {
            $error[] = '销售价大于结算价+手续费+二级供应价。';
        }
    
        $prosecond_id = $this->input->post('prosecond_id');
        if (!empty($prosecond_id)) {//二级供应商用户必须为分销商
            $result = $this->user->findByIds(array('uid'=>$prosecond_id, 'user_type'=>UTID_SELLER));
            if (!$result) {
                $error[] = '二级供应商用户uid('.$prosecond_id.')不存在或不是分销用户！';
            }
        }
        if ($this->input->post('payer') == 2) {
            if (bccomp($this->input->post('supply_price'), $this->input->post('poundage'), 3) == -1) {
                $error[] = '供应商付手续费，结算价利润必须大于手续费！';
            }
        }
        if ($this->input->post('payer') == 3 && bccomp($this->input->post('prosecond_profit'), $this->input->post('poundage'), 3) == -1) {
            $error[] = '二级供应商付手续费，利润必须大于手续费！';
        }
        return $error;
    }
    
    public function validateProfit()
    {
        $poundage     = $this->input->post('poundage') ? $this->input->post('poundage') : 0;

        $uid          = $this->input->post('uid'); //数组
        $profit       = $this->input->post('amount'); //数组
        $type_id      = $this->input->post('type_id'); //数组
        if($poundage == 0){
            if(empty($uid) && empty($profit) && empty($type_id)){
                return '';
            }else{
                return $error[] = '请仔细核对，手续费，分润金额！';
            }
        }
        $error        = $this->validateUserUid($uid); //判断用户是否存在
        if (empty($error) && !empty($profit)) {
            $amount = 0;
            foreach ($profit as $key=>$value) {
                if(!is_numeric($value) || $value < 0){
                    return $error[] = '金额必须填写大于或等于0的数字！';
                }
                if ($value >= 0) {
                    $amount += $value;
                }
            }
            if (bccomp($amount, $poundage, 3) != 0) {
                $error[] = '分润总额（'.$amount.'）与手续费（'.$poundage.'）不符`~`';
            }
        }
        return $error;
    }
    
    public function validateUserUid($uidArray)
    {
        $error = array();
        if (empty($uidArray)) {
            return $error[] = '请填写议价分润的用户信息！';
        }
        if (!is_array($uidArray)) {
            $uidArray = array($uidArray);
        }
        $result = $this->user->findByIds(array('uid'=>$uidArray));
        if (!$result) {
            return $error[] = '用户UID为'.implode($uidArray, ',').'的用户不存在';
        }
        $sellerQuery = $this->getUserNameUid($result);
        $diffArray = array_diff($uidArray, array_flip($sellerQuery));
        if (!empty($diffArray)) {
            return $error[] = '用户UID为'.implode($diffArray, ',').'的用户不存在或该用户不是分销商';
        }
        return $error;
    }
    
}